<template>
  <div class="flex flex-col h-full">
    <vxe-card title="" class="w-full" :border="false">
      <AuForm ref="formRef" :formList="formList" @submit="search" />
    </vxe-card>

    <div class="flex-grow overflow-hidden mt-4">
      <AuTable ref="tableRef" v-bind="gridOption" @actionClick="actionClick">
        <template #status_default="{ row }">
          <el-tag :type="row.publish_status === 1 ? 'success' : 'info'"
            >{{
              row.publish_status === 1
                ? t("formulaVersion.statusUp")
                : t("formulaVersion.statusDown")
            }}
          </el-tag>
        </template>
      </AuTable>
    </div>

    <AuModal
      v-model="showPopup"
      :title="
        activeType === ACTION_TYPE.TADD
          ? t('formulaVersion.addTitle')
          : t('formulaVersion.editTitle')
      "
      :width="460"
      show-zoom
      :padding="false"
      @handleConfirm="handleConfirm"
    >
      <div class="flex justify-center pt-[30px] pb-[12px] pr-[20px]">
        <AuForm
          ref="formPopRef"
          :formList="formPopList"
          :isInline="false"
          :hiddenBtn="true"
          class="!w-[400px]"
        />
      </div>
    </AuModal>

    <!--  <CheckedModal v-model="showModal" :check-list="checkList" /> -->

    <!-- <VersionEditModal
      v-model="showEditModal"
      :form-data="rowData"
      @confirm="tableRef?.refresh()"
    /> -->

    <IssueModal
      v-model="showIssueModel"
      :versionId="versionId"
      :is-only-show-store="true"
      device-id-type="ATT-G"
      :release-fn="[formulaVersionRelease, formulaVersionGetRelease]"
    />
  </div>
</template>

<script setup lang="ts">
import { getCurrentInstance, nextTick, reactive, ref } from "vue";
import { AuTable } from "@/components/AuTable";
import { AuForm } from "@/components/AuForm";
import { AuModal } from "@/components/AuModal";
import { pick } from "lodash-unified";
import { useDetail } from "../hooks";
import {
  ACTION_TYPE,
  ObjectProps,
  PropDefines
} from "@/components/AuTable/type";
import {
  getFormulaVersionList,
  versionsAdd,
  versionsUpdate,
  versionsDelete,
  updateStatus,
  formulaVersionGetRelease,
  formulaVersionRelease,
  FormulaVersionListProp
} from "@/api/cabinet/formulaVersion";
import { useRouter } from "vue-router";
/* import CheckedModal from "./components/CheckedModal.vue"; */
/* import VersionEditModal from "./components/VersionEditModal.vue"; */
import { ElMessage } from "element-plus";
import IssueModal from "@/components/Autata/IssueModal.vue";
import { VxeUI } from "vxe-table";
import { useI18n } from "vue-i18n";

defineOptions({ name: "CabinetFormulaManage" });

const { toFormulaDetail } = useDetail();
const { t } = useI18n();

// region 声明ref变量集合
const { proxy } = getCurrentInstance();
const router = useRouter();

const checkList = ref([]);
const showModal = ref(false);

const showEditModal = ref(false);
const showIssueModel = ref(false);
const versionId = ref("");
const rowData = ref<FormulaVersionListProp>();

const showPopup = ref(false); //新增、修改维护弹框
const formPopRef = ref(); //维护对象
const activeType = ref(null);

const formList = ref([
  {
    type: "input",
    label: "formulaVersion.name",
    key: "name",
    labelWidth: 40,
    placeholder: "formulaVersion.namePlaceholder"
  }
  // {
  //   type: "select",
  //   label: "formulaVersion.status",
  //   key: "publish_status",
  //   placeholder: "formulaVersion.statusPlaceholder",
  //   valueKey: "value",
  //   labelKey: "label",
  //   options: [
  //     {
  //       label: "formulaVersion.statusAll",
  //       value: ""
  //     },
  //     {
  //       label: "formulaVersion.statusUp",
  //       value: 1
  //     },
  //     {
  //       label: "formulaVersion.statusDown",
  //       value: 0
  //     }
  //   ]
  // }
]);
const gridOption = reactive<PropDefines>({
  isServerPage: true,
  showCheckbox: true,
  showIndex: false,
  columns: [
    { field: "id", title: "formulaVersion.id", align: "center" },
    { field: "name", title: "formulaVersion.name", align: "center" },
    {
      field: "formula_count",
      title: "formulaVersion.formulaList",
      align: "center"
    },
    // {
    //   field: "publish_status",
    //   title: "formulaVersion.status",
    //   slots: { default: "status_default" },
    //   align: "center"
    // },

    { field: "note", title: "table.note", align: "center" },
    {
      field: "update_time",
      title: "formulaVersion.updateTime",
      align: "center",
      width: 160
    }
    // {
    //   field: "publish_time",
    //   title: "formulaVersion.publishTime",
    //   align: "center",
    //   width: 160
    // }
  ],
  actions: [
    ACTION_TYPE.TADD,
    ACTION_TYPE.TDELETE,
    // ACTION_TYPE.TPUTAWAY,
    // ACTION_TYPE.TOFFSHELVE,
    // ACTION_TYPE.VIEW,
    ACTION_TYPE.EDIT
  ],
  operateTools: [
    /* {
      key: ACTION_TYPE.TPUTAWAY,
      name: "table.putaway",
      disableHandle: (row: any) => !(row.publish_status == 0 && row.id != null)
    },

    {
      key: ACTION_TYPE.TOFFSHELVE,
      name: "table.soldOut",
      disableHandle: (row: any) => !(row.publish_status == 1 && row.id != null)
    }, */
    {
      key: ACTION_TYPE.VIEW,
      name: "table.formulaView"
    },
    {
      key: ACTION_TYPE.ISSUED,
      name: "table.issued"
      // disableHandle: (row: any) => row.publish_status != 1
    }
  ],
  dataSource: [],
  fetchConfig: {
    query: {
      service: (params: ObjectProps) => {
        return getFormulaVersionList(params);
      },
      param: () => formRef.value.getFormData()
    }
  }
});

const formRef = ref();
const tableRef = ref();

//维护页面字段
const formPopList = ref([
  {
    type: "input",
    key: "name",
    label: "formulaVersion.name",
    placeholder: "formulaVersion.namePlaceholder",
    required: true
  },
  {
    type: "select",
    key: "copy_version",
    label: "formulaVersion.copy",
    placeholder: "formulaVersion.copyPlaceholder",
    labelKey: "name",
    valueKey: "id",
    columns: []
  },
  {
    type: "input",
    key: "note",
    label: "table.note",
    placeholder: "formulaVersion.notePlaceholder",
    inType: "textarea"
  }
]);
// endregion

// region 公共方法的集合

/**
 * 上架/下架
 * @param rows {FormulaVersionListProp[]}
 * @param status {ACTION_TYPE.OFFSHELVE | ACTION_TYPE.PUTAWAY}
 */
const handleUpOrDown = (
  rows: FormulaVersionListProp[],
  status: ACTION_TYPE.TOFFSHELVE | ACTION_TYPE.TPUTAWAY
) => {
  const name = rows.map(v => v.name);
  const ids = [];
  for (let i = 0; i < rows.length; i++) {
    ids.push({ id: rows[i].id });
  }

  const statusText =
    status === ACTION_TYPE.TOFFSHELVE
      ? t("formulaVersion.statusDown")
      : t("formulaVersion.statusUp");
  const msg = t("formulaVersion.statusChangeConfirm", {
    status: statusText,
    name: name.join("、")
  });

  proxy.$auMessageBox.confirm(msg, t("notice.title")).then(() => {
    const param = {
      publish_status: status === ACTION_TYPE.TOFFSHELVE ? 0 : 1,
      formulaList: JSON.stringify(ids)
    };
    updateStatus(param).then(res => {
      if (res.code === 200) {
        ElMessage({
          message: t("notice.operation_success"),
          type: "success"
        });
        tableRef.value.refresh();
      }
    });
  });
};

/* const handleDelete = () => {
  proxy.$auMessageBox
    .confirm("是否确认删除该物料版本？", "提示", {
      type: "error"
    })
    .then(() => {
      const checkRows = tableRef.value.getCheckboxRecords();
      if (checkRows.length > 0) {
        const ids = checkRows.map(item => item.id);
        expiryVersionDel({ ids }).then(res => {
          if (res.code === 200) {
            ElMessage({ message: `删除成功`, type: "success" });
            tableRef.value.refresh();
          }
        });
      }
    })
    .catch(() => {});
}; */
// endregion

// region 组件事件的集合
const search = () => {
  tableRef.value.refresh();
};

/* type ActionType = {
  key: ACTION_TYPE | string;
  row: ExpiryVersionProp;
}; */
const actionClick = ({ key, row }) => {
  activeType.value = key;
  switch (key) {
    case ACTION_TYPE.EDIT:
      showPopup.value = true;
      nextTick(() => {
        formPopRef.value.setFormData(row);
        formPopRef.value.setFormProps("copy_version", { hidden: true });
      });
      break;
    case ACTION_TYPE.TADD:
      showPopup.value = true;
      getPopVersion();
      nextTick(() => {
        formPopRef.value.reset();
      });
      break;
    case ACTION_TYPE.TPUTAWAY:
      const onKey = ACTION_TYPE.TPUTAWAY;
      const onList = tableRef.value.getCheckboxRecords();
      if (row.id != undefined) {
        onList.push(row);
      }
      handleUpOrDown(onList, onKey);
      break;
    case ACTION_TYPE.TOFFSHELVE:
      const offKey = ACTION_TYPE.TOFFSHELVE;
      const offList = tableRef.value.getCheckboxRecords();
      if (row.id != undefined) {
        offList.push(row);
      }
      handleUpOrDown(offList, offKey);
      break;
    case ACTION_TYPE.TDELETE:
      //handleDelete();
      proxy.$auMessageBox
        .confirm(t("formulaVersion.deleteConfirm"), t("notice.title"), {
          type: "error"
        })
        .then(() => {
          const checkedNodes = tableRef.value.getCheckboxRecords();
          console.log(checkedNodes);
          if (checkedNodes.length > 0) {
            const ids = checkedNodes.map(item => ({ id: item.id }));
            versionsDelete({ delList: JSON.stringify(ids) }).then(res => {
              if (res.code === 200) {
                VxeUI.modal.message({
                  content: t("notice.operation_success"),
                  status: "success"
                });
                tableRef.value.refresh();
              }
            });
          }
        })
        .catch(() => {});
      break;
    case ACTION_TYPE.ISSUED:
      versionId.value = String(row.id);
      showIssueModel.value = true;
      break;
    case ACTION_TYPE.VIEW: //查看配方
      // toFormulaDetail(pick(row, ["id", "name"]) as {}, "query");
      router.push({
        name: "CabinetFormulaList",
        query: {
          version: JSON.stringify({
            id: row.id,
            name: row.name
          })
        }
      });
      break;
    default:
      break;
  }
};

const getPopVersion = () => {
  const params = {
    start_page: 1,
    size: 0
  };
  getFormulaVersionList(params).then(res => {
    // formPopList.value[2].options = res.data;
    formPopRef.value.setFormProps("copy_version", {
      options: res.data,
      hidden: false
    });
  });
};

const handleConfirm = async () => {
  const validate = await formPopRef.value.validate();
  if (!validate.check) return;

  let formData = formPopRef.value.getFormData();
  let api = versionsAdd;
  if (activeType.value === "add") {
    api = versionsAdd;
  } else if (activeType.value === "edit") {
    api = versionsUpdate;
    formData = pick(formData, ["id", "name", "note"]);
  }
  api(formData).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: formData.id
          ? t("formulaVersion.editSuccess")
          : t("formulaVersion.addSuccess"),
        type: "success"
      });
      showPopup.value = false;
      tableRef.value.refresh();
      //xGrid.value.commitProxy("query");
    }
  });
  /* const validate = await formPopRef.value.validate();
  if (!validate.check) return;
  let formData = formPopRef.value.getFormData();
  let api = versionsAdd;
  if (activeType.value === "add") {
    api = versionsAdd;
  } else if (activeType.value === "edit") {
    api = versionsUpdate;
    formData = pick(formData, ["id", "name", "furnace_temp", "note"]);
  }
  api(formData).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: formData.id ? "修改配方版本成功" : "新增配方版本成功",
        type: "success"
      });
      showPopup.value = false;
      xGrid.value.commitProxy("query");
    }
  }); */
};
// endregion
</script>
